package org.utils.security;

import java.security.MessageDigest;

public class SecurityUtils
{
	public static final String DEFAULT_ALGORITHM = "SHA-1";

	public static byte[] encryptPassword(String password)
	{
		return encryptPassword(password, DEFAULT_ALGORITHM);
	}

	public static boolean checkPassword(String password, byte[] encryptedPassword)
	{
		return checkPassword(password, encryptedPassword, DEFAULT_ALGORITHM);
	}

	public static byte[] encryptPassword(String password, String algorithmName)
	{
		try
		{
			MessageDigest algorithm = MessageDigest.getInstance(algorithmName);
			algorithm.reset();
			algorithm.update(password.getBytes());
			byte[] digest = algorithm.digest();
			//return new String(digest);
			return digest;
		}
		catch (Exception e)
		{
			throw new SecurityException(e.toString());
		}
	}

	public static boolean checkPassword(String password, byte[] encryptedPassword, String algorithmName)
	{
		byte[] testedPassword = encryptPassword(password, algorithmName);
		for (int i = 0; i < encryptedPassword.length; i++)
		{
			if (encryptedPassword[i] != testedPassword[i])
			{
				return false;
			}
		}
		return true;
	}
}